package com.cloud.lan.service.task;

import com.cloud.lan.api.dto.req.WxDataReq;
import com.cloud.lan.entity.constant.WxDataConstant;
import com.cloud.lan.entity.enums.RedisKeyEnum;
import com.cloud.lan.service.impl.RedisService;
import com.cloud.lan.service.tx.wx.WxInitService;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

import javax.annotation.Resource;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 * @author ErKang
 * @date Created in 2022/1/6 01:06
 * @title TestTask.java
 * Department: Product development
 */
@Component
@Configuration
@Slf4j
@EnableScheduling
public class WxDataTask {

    @Resource
    WxInitService wxInitService;
    @Resource
    RedisService redisService;

    public static void main(String[] args) {
        String e = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1).toJdkDate(), "yyyyMMdd");
        String d = "20220119";
        System.out.println(Long.parseLong(e) > Long.parseLong(d));
        System.out.println(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1).toJdkDate(), "yyyyMMdd"));
    }

    /**
     * 每*分钟执行一次
     */
    @Scheduled(cron = "0 0/60 * * * ?")
    private void checkWxDataTask() {
        try {
            String accessToken = wxInitService.getAccessToken();
            for (String me : WxDataConstant.wxMethad) {
                log.info("# 执行微信统计 定时任务 方法：{}", me);
                WxDataReq req = new WxDataReq();
                String date = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1).toJdkDate(), "yyyyMMdd");
                req.setBegin_date(date);
                req.setEnd_date(date);
                Map<String, Object> map = Convert.convert(new TypeReference<Map<String, Object>>() {}, req);
                String mapParams = JSONUtil.toJsonStr(map);
                String url = StrUtil.format(WxDataConstant.wxDataUrl, WxDataConstant.getMethod.apply(me), accessToken);
                String result = HttpUtil.post(url, mapParams);
                if (!result.contains("errcode")) {
                    redisService.set(RedisKeyEnum.WX_DATA_METHOD.key(me), result);
                    log.info("# 执行微信统计 定时任务 完成：{} ， 返回：{}", me, result);
                }
            }
        } catch (Exception e) {
            log.error("#定时任务 checkWxDataTask 错误 :", e);
        }
    }
}
